package com.intel.factorytest;

import java.util.ArrayList;
import java.util.List;

import com.intel.factorytest.FactoryTest;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.content.Intent;

import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import android.content.res.Configuration;
import android.widget.Button;
import android.util.Log;

import android.os.SystemProperties;
import android.os.SystemClock;

import com.intel.factorytest.util.Util;
import com.intel.factorytest.util.LogUtils;

public class MainActivity extends Activity implements OnItemClickListener {
    private static final String TAG = "MainActivity";

    private static final String TEST_ITEM = "test_item";
    private static final String ITEM_NAME = "item_name";
    private static final String test_type = "FACTORY_TEST_TYPE";
    private static final String TEST_ITEM_RESULT = "test_item_result";
    private static final String sys_service = "SYSTEM_SERVICE_TEST";

    ListView listView;
    private int mTestType;
    private ResultDataSave mTestResultData;
    private String mTestItemName;

    List<Map<String, Object>> mTestGridItems = null;

    private Thread mChamberModeSetPropThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.main_list_view);
        listView.setOnItemClickListener(this);
        List<String> list = new ArrayList<String>();
        String autoTest = getString(R.string.factorytest_test_all);
        String manu_test = getString(R.string.manu_test);
        String testResult = getString(R.string.factorytest_bunch_result);
        String delResult = getString(R.string.factorytest_item_delete_result);
        String resetPhone = getString(R.string.reset_phone);
        String chamberMode = getString(R.string.chamber_mode);
        String band_tx = getString(R.string.band_tx);
        list.add(autoTest);
        list.add(manu_test);
        list.add(testResult);
        list.add(delResult);
        list.add(resetPhone);
        //list.add(chamberMode);        
        //list.add(band_tx);
        /*
        //for test
        list.add("wifi tx");        
        list.add("BT tx");        
        list.add("lte tx");        
        list.add("gps tx");
        //for test end
        */
        ItemAdapter adapter = new ItemAdapter(getApplicationContext(), list);
        listView.setAdapter(adapter);

        Configuration mConfiguration = getResources().getConfiguration();
        String localeString = mConfiguration.locale.getCountry();
        Log.d(TAG, " localeString = " + localeString);
        localeString = "US";
        mTestType = ResultDataSave.SYSTEM_ITEM_TEST;
        mTestGridItems = ConfigFileParseUtil.getConfParserConcrete(this,
                AConfigFileParser.EXTENSION_PROPERTISE).doParse(1, 0,
                localeString, null);

        Log.d(TAG, " mTestGridItems = " + mTestGridItems);
        mTestResultData = new ResultDataSave();
        mTestResultData.initResultData(this, mTestType, mTestGridItems);
        initResultFile();
        //LogWriter.enable();
    }

    protected void onResume() {
        Log.d(TAG, "onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.d(TAG, "onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        Log.d(TAG, "onStop");
        super.onStop();
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("mTestItemName", mTestItemName);
        super.onSaveInstanceState(outState);
        Log.d(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        mTestItemName = savedInstanceState.getString("mTestItemName");
        super.onRestoreInstanceState(savedInstanceState);
        Log.d(TAG, "onRestoreInstanceState");
    }

    private class ItemAdapter extends BaseAdapter {
        List<String> mList;
        Context mContext;

        public ItemAdapter(Context context, List<String> list) {
            mList = list;
            mContext = context;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return mList == null ? null : mList.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            if (arg1 == null) {
                LogUtils.logi("mContext" + mContext);
                LogUtils.logi("arg1" + arg1 + ",arg0 = " + arg0);
                arg1 = LayoutInflater.from(mContext).inflate(R.layout.main_item, null);
                TextView itemName = (TextView) arg1.findViewById(R.id.test_mode);
                itemName.setText(mList.get(arg0));
            }
            return arg1;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        switch (arg2) {
            case 0:
                //auto test;
                Log.d(TAG, " auto test.");
                autoTest();
                break;
            case 1:
                //manu test;
                Intent intent = new Intent(MainActivity.this, FactoryTest.class);
                startActivity(intent);
                break;
            case 2:
                //testresult;
                Intent testResultIntent = new Intent();
                testResultIntent.setClassName("com.intel.factorytest",
                        "com.intel.factorytest.FactoryTestResultShow");
                startActivity(testResultIntent);
                break;
            case 3:
                //del result;
                BuildDeleteDialog();
                break;
            case 4:
                Intent resetPhoneIntent = new Intent();
                resetPhoneIntent.setClassName("com.intel.factorytest",
                        "com.intel.factorytest.activity.ResetPhoneActivity");
                startActivity(resetPhoneIntent);
                //reset phone;
                break;
            case 5:
                mChamberModeSetPropThread = new Thread(new ChamberModeSetPropRunnable());
                mChamberModeSetPropThread.start();

                SystemProperties.set("persist.sys.chamber.bandtest", "null");

                Intent chamberModeIntent = new Intent();
                chamberModeIntent.setClassName("com.intel.factorytest",
                        "com.intel.factorytest.ChamberMode.ChamberModeMainActivity");
                startActivity(chamberModeIntent);
                break;
            case 6:
                SystemProperties.set("persist.sys.chamber.bandtest", "null");
                Intent bandtxIntent = new Intent();
                bandtxIntent.setClassName("com.intel.factorytest",
                        "com.intel.factorytest.bandtx.BandTest");
                startActivity(bandtxIntent);
                break;
        /*
        //for test
        case 7:
            Intent wifitxIntent = new Intent();
            wifitxIntent.setClassName("com.intel.factorytest",
                    "com.intel.factorytest.ChamberMode.WifiTest");
            startActivity(wifitxIntent);
            break;
        case 8:
            Intent bttxIntent = new Intent();
            bttxIntent.setClassName("com.intel.factorytest",
                    "com.intel.factorytest.ChamberMode.BluetoothTest");
            startActivity(bttxIntent);
            break;
        case 9:
            Intent ltetxIntent = new Intent();
            ltetxIntent.setClassName("com.intel.factorytest",
                    "com.intel.factorytest.ChamberMode.LTEBandTest");
            startActivity(ltetxIntent);
            break;
        case 10:
            Intent gpstxIntent = new Intent();
            gpstxIntent.setClassName("com.intel.factorytest",
                    "com.intel.factorytest.ChamberMode.GnssTest");
            startActivity(gpstxIntent);
            break;  
        //for test end
        */
        }
    }

    void BuildDeleteDialog() {
        AlertDialog.Builder builder = new Builder(this);
        builder.setMessage(getString(R.string.factorytest_delete_result_note));
        builder.setTitle(getString(R.string.factorytest_delete_result_title));
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.del_result_dialog_result, null);
        Button ok = (Button) view.findViewById(R.id.del_ok);
        Button cancel = (Button) view.findViewById(R.id.del_cancel);
        builder.setView(view);

        final AlertDialog dialog = builder.create();
        //add by wangsm
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTestResultData.DeleteResult(getBaseContext(), mTestType);
                mTestResultData.SaveResultData(getBaseContext(), mTestType, mTestGridItems);
                resetResultData();
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void autoTest() {
        Map map = (Map) mTestGridItems.get(0);
        mTestItemName = (String) map.get("itemName");
        Log.d(TAG, " auto test.mTestItemName " + mTestItemName);
        Intent intent = (Intent) map.get("intent");
        intent.putExtra(sys_service, 1);
        intent.putExtra(TEST_ITEM, 0);
        intent.putExtra(ITEM_NAME, mTestItemName);
        //intent.putExtra(LogWriter.LogFileNameTag, logFileName);
        //mIsTestAll = TEST_ALL_ITEM;
        try {
            startActivityForResult(intent, 0);
        } catch (Exception e) {
            Log.e(TAG, "error");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Boolean is_pass;
        int test_pos;
        //Log.d(TAG, " Factory tets onActivityResult");
        Log.d(TAG, "onActivityResult data =" + data);
        Log.d(TAG, "onActivityResult mTestItemName=" + mTestItemName);

        if (data != null && mTestItemName != null) {
            is_pass = data.getBooleanExtra(TEST_ITEM_RESULT, false);
            test_pos = data.getIntExtra(TEST_ITEM, -1);

            Log.d(TAG, "pos = " + test_pos + " name = " + mTestItemName);
            String versionTest = getString(R.string.version_test);
            String testTorch = getString(R.string.torch_test);
            String testBacklight = getString(R.string.backlight_test);
            String testBluetooth = getString(R.string.bluetooth_test);
            String testWifi = getString(R.string.wifi_test);
            String testMicrophoneSub = getString(R.string.microphone_sub_test);
            if (mTestItemName.equals("System Info")
                    || mTestItemName.equals("LED")
                    || mTestItemName.equals("Audio Jack")
                    || mTestItemName.equals("Back mic")
                    || mTestItemName.equals("Top Front mic")
                    || mTestItemName.equals("Bottom Front mic")
                    || mTestItemName.equals("Earpiece 1Khz")
                    || mTestItemName.equals("Earpiece Music")
                    || mTestItemName.equals("Speaker 1Khz")
                    || mTestItemName.equals("Speaker music")
                    || mTestItemName.equals("Touch screen")
                    || mTestItemName.equals("Display Brightness")
                    || mTestItemName.equals("Display Pattern")
                    || mTestItemName.equals("Back Camera")
                    || mTestItemName.equals("Camera back Flash")
                    || mTestItemName.equals("Front Camera")
                    || mTestItemName.equals("Micro SD Card")
                    || mTestItemName.equals("Nano Sim")
                    || mTestItemName.equals("Vibrator")
                    || mTestItemName.equals("Sensors")
                    || mTestItemName.equals("Battery")
                    || mTestItemName.equals("Bluetooth test")
                    || mTestItemName.equals("Wifi test")
                    || mTestItemName.equals("GPS Location")
                    || mTestItemName.equals("Earpiece 1Khz")
                    || mTestItemName.equals("Speaker 1Khz")
                    || mTestItemName.equals("Key & Button")
                    || mTestItemName.equals("Top Front mic")
                    || mTestItemName.equals("SARSensor")
                    || mTestItemName.equals("Volume Knob")
                    || mTestItemName.equals("Mic Test")
                    || mTestItemName.equals("Sub Mic Test")
                    || mTestItemName.equals("USB")
                    || mTestItemName.equals("FM Test")
                    || mTestItemName.equals("RTC")
                    || mTestItemName.equals("Call Test")
                    || mTestItemName.equals("OTG test")
                    || mTestItemName.equals("AOV test")
            ) {
                if (is_pass) {
                    mTestResultData.setDataOfList(mTestType, mTestItemName,
                            test_pos, ResultDataSave.ITEM_TEST_SUCCES);
                } else {
                    mTestResultData.setDataOfList(mTestType, mTestItemName,
                            test_pos, ResultDataSave.ITEM_TEST_FAIL);
                }

                mTestResultData.SaveResultData(this, mTestType, mTestGridItems);//add by wangsm for save data
                if (is_pass) {
                    mTestResultData.resultSaveToFile(test_pos, '1');
                } else {
                    mTestResultData.resultSaveToFile(test_pos, '0');
                }
                if (test_pos + 1 < mTestGridItems.size()) {
                    Map map = (Map) mTestGridItems.get(test_pos + 1);
                    Intent intent = (Intent) map.get("intent");
                    intent.putExtra(TEST_ITEM, test_pos + 1);
                    intent.putExtra(sys_service, 1);
                    intent.putExtra(ITEM_NAME, (String) map.get("itemName"));
                    //intent.putExtra(LogWriter.LogFileNameTag, logFileName);
                    mTestItemName = (String) map.get("itemName");
                    startActivityForResult(intent, test_pos + 1);//FactoryTest.this.
                    return;
                }
            }
        }
    }

    private void initResultFile() {
        String resultLine = ResultDataSave.readResultFile();
        if (resultLine != null) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        if (mTestGridItems != null) {
            for (int i = 0; i < mTestGridItems.size(); i++) {
                sb = sb.append("0");
            }
            ResultDataSave.initFactoryResultFile(sb.toString());
        }
    }

    private void resetResultData() {
        StringBuilder sb = new StringBuilder();
        if (mTestGridItems != null) {
            for (int i = 0; i < mTestGridItems.size(); i++) {
                sb = sb.append("0");
            }
            ResultDataSave.initFactoryResultFile(sb.toString());
        }
    }

    private class ChamberModeSetPropRunnable implements Runnable {
        @Override
        public void run() {
            String chambermodebefor = Util.getSystemProperties("persist.sys.chamber_mode", "null");
            LogUtils.logi("ChamberModeSetPropRunnable getSystemProperties chambermodebefor = " + chambermodebefor);
            SystemProperties.set("persist.sys.chamber_mode", "Chamber");
            SystemClock.sleep(500);
            String chambermode = Util.getSystemProperties("persist.sys.chamber_mode", "null");
            LogUtils.logi("ChamberModeSetPropRunnable getSystemProperties  chambermode = " + chambermode);
        }
    }
}